/**
* @Author: zmx
* @Date: 2023/9/25
* @Description:
*/
<template>
  <div>
    <el-col :span="10">
      <div style="padding: 20px">
        <el-form :inline="true" :model="formInline">
          <el-row>
<!--            <el-col :span="20">-->
<!--              <el-form-item>-->
<!--                <el-button type="primary" @click="importMe">导入</el-button>-->
<!--              </el-form-item>-->
<!--              <el-form-item>-->
<!--                <el-button type="primary" @click="exportMe">导出</el-button>-->
<!--              </el-form-item>-->
<!--            </el-col>-->
            <el-form-item>
              <el-button type="primary" @click="clickExport">导出</el-button>
            </el-form-item>

<!--            <input type="file" accept=".xlsx" ref="filebox" id="fileinput" style="display: none;" @change="checkFileSure">-->
            <el-form-item>
<!--              <el-button type="primary" @click="clickImport">导入</el-button>-->
              <el-upload
                action
                class="upload-demo"
                :http-request="checkFileSure"
                :file-list="fileList">
                <el-button size="small" type="primary">导入</el-button>
              </el-upload>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="newTag">新增节点</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="newEdge">新增关系</el-button>
            </el-form-item>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="充电桩品牌：">
                <el-select
                    v-model="formInline.deviceFactory"
                    value-key="id"
                    filterable
                    clearable
                    @change="getDistrict"
                >
                  <el-option
                      v-for="item in optionsBrandList"
                      :key="item.value"
                      :label="item.name"
                      :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="对象类型：">
                <el-select
                    v-model="formInline.modelType"
                    value-key="id"
                    filterable
                    clearable
                    @change="selectModel"
                >
                  <el-option
                      v-for="item in optionsModeTypeList"
                      :key="item.itemObjectName"
                      :label="item.itemObjectName"
                      :value="item.itemObjectName"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="故障等级：">
                <el-select
                    v-model="formInline.faultValue"
                    value-key="id"
                    filterable
                    clearable
                >
                  <el-option
                      v-for="item in optionsFaultClassList"
                      :key="item.faultValue"
                      :label="item.faultClass"
                      :value="item.faultValue"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="8">
              <el-form-item label="故障代码">
                <el-input v-model="formInline.faultCode" placeholder="请输入故障代码查询"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="故障名称">
                <el-input v-model="formInline.faultName" placeholder="请输入故障名称查询"></el-input>
              </el-form-item>
            </el-col>

          </el-row>
          <el-form-item>
            <el-button type="primary" @click="search">查询</el-button>
          </el-form-item>

        </el-form>
        <el-table highlight-current-row :data="tableData" style="width: 100%" :header-cell-style="{background:'#006175',color:'#fff'}" @row-click="handleRowClick">
<!--          <el-table-column prop="deviceFactory" label="品牌名称"></el-table-column>-->
          <el-table-column prop="faultCode" label="故障代码"></el-table-column>
          <el-table-column prop="faultName" label="故障名称" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column prop="faultReason" label="故障原因" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column prop="faultValue" label="故障等级" :formatter="formatFaultClass"/>
        </el-table>
        <el-pagination
            style="margin-top: 20px"
            :page-size="formInline.pageSize"
            layout="total, sizes, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="formInline.pageNumber"
            :total="formInline.total">
        </el-pagination>
            <modelDialog v-if="ModelDialogShow"
                         :ModelDialogShow="ModelDialogShow"
                         :modelParam="modelParam"
                         @closeDialog="closeDialog"></modelDialog>
            <modelEdgeDialog v-if="ModelEdgeDialogShow"
                     :ModelDialogShow="ModelEdgeDialogShow"
                     :modelParam="modelParam"
                     @refreshGraph="refreshGraph"
                     @closeDialog="closeEdgeDialog"></modelEdgeDialog>
      </div>
    </el-col>
    <el-col :span="14">
<!--      图谱 -->
      <div style="background: white;margin: 20px;border:1px solid rgba(69,69,69,1);height: 100vh" id="container"></div>
    </el-col>
  </div>
</template>

<script>
import {
  queryTreat,
  treatDetail,
  showGraph,
  queryFaultClass,
  exportGraph,
  importGraph,
  exportTag, importTag
} from "../../../../api/fault/index"
import {plan} from '../../../../api/inspection/apiUntil'
import {formatDate} from "@/utils/DateFormat"
import modelDialog from "./addDialog";
import modelEdgeDialog from "./addEdgeDialog";
import G6 from '@antv/g6';
import {getItemDictObject} from "../../../../api/risk/commonDict";

export default {
  components: {
    modelDialog,
    modelEdgeDialog
  },
  data() {
    return {
      uploadForm: new FormData(),
      startVid: '充电桩',
      graph: null,
      fileList:[],
      option: [],
      tableData: [],
      optionsListCity: [],
      optionsListDistrict: [],
      optionsBrandList: [
        {
          key:'POTEVIO普天',
          value:'POTEVIO普天'
        },
        {
          key:'奥特迅',
          value:'奥特迅'
        },
        {
          key:'TITANS泰坦',
          value:'TITANS泰坦'
        },
        {
          key:'特来电',
          value:'特来电'
        },
      ],
      optionsModeTypeList: [],
      optionsFaultClassList: [],
      formInline: {
        deviceFactory: '',
        districtId: '',
        stationId: '',
        deviceName: '',
        deviceType: '',
        faultValue: '',
        pageSize: 10,
        pageNumber: 1,
        total: 0
      },
      modelParam: {},
      actionParam: {
        modelId: '',
        modelType: '',
        action: ''
      },
      ModelDialogShow: false,
      ModelEdgeDialogShow: false,
    };
  },
  mounted() {
    this.getInit()
    this.initNebula()
    getItemDictObject().then((res)=>{
      if(res){
        this.optionsModeTypeList = res
      }
    }).catch(err => {
      this.$message({ message: '服务器异常：' + err, type: 'warning' })
    })
    queryFaultClass().then((res) => {
      if (res) {
        this.optionsFaultClassList = res.data
        console.log(this.optionsFaultClassList,'====')
      }
    })
  },
  methods: {
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.getInit()
    },
    initNebula() {
      const width = document.getElementById('container').scrollWidth;
      const height = document.getElementById('container').scrollHeight || 500;
      this.graph = new G6.Graph({
        container: 'container',
        width: width,
        height: height,
        layout: {
          type: 'force',
          preventOverlap: true,
          nodeSize: 180
        },
        animate: true,
        modes: {
          // 支持的 behavior
          default: [ 'drag-node' , 'drag-canvas', 'scroll-canvas']
        },
        defaultNode: {
          type: 'circle',
          size: [130],
          labelCfg: {
            style: {
              fill: '#fff',
              fontSize: 27,
            },
          },
        },
        defaultEdge: {
          color: '#e2e2e2',
        },
      });

      this.refreshGraph()
    },
    formaTime(row, col) {
      return formatDate("YYYY-mm-dd HH:MM:SS", row[col.property])
    },
    search() {
      this.refreshPageByCondition()
      this.refreshGraph()
    },
    reset() {
      this.formInline.deviceFactory = ''
      this.formInline.districtId = ''
      this.formInline.stationId = ''
      this.formInline.deviceName = ''
      this.formInline.deviceType = ''
      this.formInline.faultValue = ''
      this.search()
    },
    async detailRule(model) {
      this.modelParam.type = 'detail'
      await this.getModelParam(model)
      this.ModelDialogShow = true
    },
    async getModelParam(model) {
      await this.getDetail(model.id)
      this.modelParam.modelId = model.id
      this.modelParam.modelName = model.modelName
      this.modelParam.modelType = model.modelType
      this.modelParam.modelRule = model.ruleId
    },
    async getDetail(modelId) {
      await treatDetail({faultId: modelId}).then((res) => {
        this.modelParam.model = res.data
      })
    },
    closeDialog() {
      this.ModelDialogShow = false
    },
    closeEdgeDialog() {
      this.ModelEdgeDialogShow = false
    },
    getInit() {
      this.refreshPageByInit()
      this.getCity()
    },
    refreshPageByInit() {
      this.refreshPage({})
    },
    refreshPageByCondition() {
      let params = {
        deviceFactory: this.formInline.deviceFactory,
        districtId: this.formInline.districtId,
        stationId: this.formInline.stationId,
        faultName: this.formInline.faultName,
        faultCode: this.formInline.faultCode,
        faultValue: this.formInline.faultValue
      }
      this.refreshPage(params)
    },
    refreshPage(params) {
      params.pageNumber = this.formInline.pageNumber
      params.pageSize = this.formInline.pageSize
      queryTreat(params).then((res) => {
        if (res) {
          this.tableData = res.data.list
          this.formInline.total = res.data.listSize
        }
      })
    },
    handleCurrentChange(val) {
      this.formInline.pageNumber = val
      this.getInit()
    },
    getCity() {
      plan.getPlanCity().then((res) => {
        if (res) {
          this.optionsListCity = res.data
        }
      })
    },
    getDistrict() {
      let params = {
        code: this.formInline.deviceFactory
      }
      plan.getPlanDist(params).then((res) => {
        if (res) {
          this.optionsListDistrict = res.data
        }
      })
    },
    getStation() {
      let params = {
        code: this.formInline.districtId
      }
      plan.getPlanStat(params).then((res) => {
        if (res) {
          this.optionsListStation = res.data
        }
      })
    },
    newTag() {
      this.ModelDialogShow = true
    },
    newEdge() {
      this.ModelEdgeDialogShow = true
    },
    refreshGraph() {
      showGraph({
        "edge": "withP",
        "vid": this.startVid
      }).then((res) => {
        let data = res.data
        data.nodes.map(node => {
          let chunkedString = "";
          for (let i = 0; i < node.label.length; i += 3) {
            const chunk = node.label.slice(i, i + 3);
            chunkedString += chunk;
            if (i + 3 < node.label.length) {
              chunkedString += "\n";
            }
          }
          // console.log(node.properties)
          node.size = node.properties?node.properties.size:'53'

          node.label = chunkedString
          node.style =
              {
                fill: node.properties?node.properties.color:'#2A82E4',
                stroke: node.properties?node.properties.color:'#2A82E4'
              }
          node.labelCfg = {
            positions: 'center',// 标签的属性，标签在元素中的位置
            style: {            // 包裹标签样式属性的字段 style 与标签其他属性在数据结构上并行
              fontSize: node.properties?node.properties.fontSize:'12'      // 标签的样式属性，文字字体大小
            }
          }
        })
        this.graph.data(data)
        this.graph.render()
      })
    },
    handleRowClick(row) {
      this.startVid = row.faultName
      this.refreshGraph()
    },
    selectModel() {
      this.startVid = this.formInline.modelType
    },
    formatFaultClass(row, col) {
      let obj = this.optionsFaultClassList.find((r) => row[col.property].toString() === r.faultValue.toString())
      if (obj) {
        return obj.faultClass
      }
      return row[col.property]
    },
    clickExport() {
      exportGraph().then((res) => {
        const blob = new Blob([res], {
          type: "application/octet-stream"
        })
        // 获取heads中的filename文件名
        const downloadElement = document.createElement('a')
        // 创建下载的链接
        downloadElement.href = window.URL.createObjectURL(blob)
        // 下载后文件名
        downloadElement.download = "图谱关系.xlsx"
        document.body.appendChild(downloadElement)
        // 点击下载
        downloadElement.click() // 下载完成移除元素
        document.body.removeChild(downloadElement)
      })
    },
    clickImport() {
      document.querySelector('#fileinput').click()
    },
    checkFileSure(file) {
      this.$confirm('确认导入"' + document.querySelector('#fileinput').files[0].name + '"吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.uploadForm.append('file', file.file);
        importGraph(this.uploadForm).then((res) => {
          if (res.code === 200) {
            this.$message({
              message: "导入成功",
              type: "success",
            });
            this.refreshGraph()
            this.fileList = []
          }else {
            this.$message.error('导入失败：' + res.msg);
          }
        })

      }).finally(() => {
        document.querySelector('#fileinput').value = '';
        this.$refs.filebox.value = '';
        this.uploadForm = new FormData()
        console.log(document.querySelector('#fileinput').files[0]);
        this.fileName = "";
      });
    }
  }
}
</script>

<style scoped>

</style>
